<?php
/**
 * 商圈模型
 */

namespace app\admin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class BusinessArea extends BaseModel {

    /**
     * 筛选多条数据
     * @param array|null $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getDatas(?array $map, $column) {
        return db('business_area')
            ->where($map)
            ->field($column)
            ->select();
    }

    /**
     * 筛选单条数据
     * @param array|null $map
     * @param $column
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOne(?array $map, $column) {
        return Db::name('business_area')
            ->where($map)
            ->field($column)
            ->find();
    }

    /**
     * 省市区联动-区域下面的商圈
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getAreaBus($params) {
        $house = House::getOne([['id', '=', $params['id']]], 'city_codes');
        $city_codes = explode(',', $house['city_codes']);
        if (!empty($city_codes[3])) {
            $data = self::getDatas([['city_id', '=', $city_codes[3]]], 'name,id');
            foreach ($data as $k => $v) {
                $data[$k]['rank'] = 4;
            }
            return $data;
        } else {
            return [];
        }
    }

    /**
     * 区域商圈列表
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function businessList($params) {
        $city_code = $params['city_code'];
        $column = ['name', 'city_code', 'id', 'weights', 'house_number', 'total_number','avg_price'];
        //该市下面所有区域
        $list = db::name('region')
            ->where('p_code', $city_code)
            ->order('weights asc')
            ->field($column)
            ->select();
        foreach ($list as $k1 => $v1) {
            $list[$k1]['end_number'] = $v1['total_number'] - $v1['house_number'];
            $list[$k1]['avg_price'] = moneyFormat($list[$k1]['avg_price'],2);
        }
        $ids = array_column($list, 'city_code');
        //区域下面所有商圈
        $business_area = db::name('business_area')
            ->where('city_id', 'in', $ids)
            ->field('name,city_id,id,house_number,total_number')
            ->select();
        $list = array_column($list, null, 'city_code');
        foreach ($business_area as $k2 => $v2) $business_area[$k2]['end_number'] = $v2['total_number'] - $v2['house_number'];
        foreach ($business_area as $v3) if (isset($list[$v3['city_id']])) $list[$v3['city_id']]['children'][] = $v3;
        $list = array_values($list);
        for ($i1 = 0; $i1 < count($list); $i1++) if (empty($list[$i1]['children'])) $list[$i1]['children'] = [];
        return $list;
    }

    /**
     * 编辑
     * @param $params
     * @return bool
     * @throws Exception
     * @throws PDOException
     */
    public static function edit($params) {
        $data = db("business_area")->where('id', $params['businessAreaId'])->find();
        if (empty($data)) {
            Err::add('数据不存在');
            return false;
        }
        if (mb_strlen(trim($params['name']), 'utf-8') > 30) {
            Err::add('名称长度限制30', RespCode::DATA_ERR);
            return false;
        }
        $exists = db("business_area")->where('name', $params['name'])->select();
        if ($data['name'] != $params['name']) {
            if ($exists) {
                Err::add('该商圈名已存在');
                return false;
            }
        }
        $p_codes = Region::where('city_code', $params['city_code'])
            ->value('p_codes');
        if (empty($p_codes)) {
            Err::add('错误的city_code');
            return false;
        }
        $update = [
            'city_id'  => $params['city_code'],
            'city_ids' => $p_codes . $params['city_code'] . ',',
            'name'     => $params['name'],
            'location' => Db::raw("POINT('{$params['lng']}', '{$params['lat']}')"),
            'lat'      => $params['lat'],
            'lng'      => $params['lng'],
        ];
        self::where('id', $params['businessAreaId'])->update($update);
        return true;
    }

    /**
     * 获取名称
     * @param $params
     * @return bool
     */
    public static function get_Name($params, &$res) {
        $data = db('business_area')
            ->where('id', $params['businessAreaId'])
            ->field('x(location) as lng,Y(location) as lat,name,city_id as city_code')
            ->find();
        if (empty($data)) {
            Err::add('数据不存在');
            return false;
        }
        $res['name'] = $data['name'];
        $res['lng'] = $data['lng'];
        $res['lat'] = $data['lat'];
        $res['city_code'] = $data['city_code'];
        return true;
    }

    /**
     * 编辑获取上级区域
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function upArea($params) {
        $city_ids = self::where('id', $params['businessAreaId'])->value('city_ids');
        $city_ids_array = explode(',', $city_ids);
        return Region::getDatas([['p_code', '=', $city_ids_array[2]]], 'city_code,name');
    }

    /**
     * 删除
     * @param $params
     * @return bool
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public static function deleted($params) {
        if (empty(db("business_area")->where('id', $params['businessAreaId'])->find())) {
            Err::add('数据不存在', RespCode::DATA_ERR);
            return false;
        }
        if (Db::name("house")->where('business_area_id', $params['businessAreaId'])->select()) {
            Err::add('该商圈有关联房源', RespCode::DATA_ERR);
            return false;
        }
        if (Db::name("house_village")->where('business_area', $params['businessAreaId'])->select()) {
            Err::add('该商圈有关联小区', RespCode::DATA_ERR);
            return false;
        }
        self::where('id', $params['businessAreaId'])->delete();
        return true;
    }

}
